package main

import "fmt"
import "net"

import "net/http"
import "io/ioutil"

import "encoding/json"
import "time"

type MUser struct {
	Name  string `json:name,omitempty`
	Uid   int    `json:uid,omitempty`
	Uname string `json:uname,omitempty`
	Aid   int    `json:aid,omitempty`
}
type LUser struct {
	Code int    `json:code`
	Msg  string `json:msg,omitempty`
	Data MUser  `json:data,omitempty`
}

func httpGet(url string, data map[string]string) string {
	if len(data) != 0 {
		url += "?"
		for v, i := range data {
			url += v + "=" + i + "&"
		}
	}

	resp, err := http.Get(url)

	if err != nil {

		// handle error

	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {

		// handle error

	}

	return string(body)
}
func GetPage(c net.Conn) {

}
func CharDele(s string) string {
	if len(s) <= 2 {
		return s
	}
	if s[len(s)-2:len(s)] == "\r\n" {
		return s[:len(s)-2]
	}
	return s
}
func ParmarHandle(s string, c net.Conn, u *LUser, islogin *bool) {

	s = CharDele(s)
	// fmt.Println("Char:", s)
	// fmt.Println("charb:", []byte(s))
	if s == "/HELP" || s == "/help" {
		c.Write([]byte("\033[42;33m####欢迎使用帮助文件#### \033[0m\r\n\r\n"))
		c.Write([]byte("\033[42;33m/LOGin 登陆\r\n/register 注册用户\r\n/LOGOUT 退出登陆\r\n/VIEW 浏览模式\r\n/WRITE 发新帖子\r\n/REPLY 回帖\r\n/exit 退出论坛程序\033[0m\r\n\033[41;36m/cls 清屏\r\n/myself 用户信息\r\n/about 关于\033[0m\r\n\r\n>"))
	} else if s == "/exit" || s == "/EXIT" {
		c.Close()
	} else if s == "/LOGIN" || s == "/login" {
		c.Write([]byte("请输入你的用户名:\r\nlogin>"))
		User := ""
		Pwd := ""
		tmp := make([]byte, 128)
		for {
			n, _ := c.Read(tmp)
			if string(tmp[:n]) == "\r\n" {
				continue
			}
			User = string(tmp[:n])
			break
		}
		c.Write([]byte("请输入你的密码:\r\nlogin>"))

		for {
			n, _ := c.Read(tmp)
			if string(tmp[:n]) == "\r\n" {
				continue
			}
			Pwd = string(tmp[:n])
			break
		}
		data := make(map[string]string)
		data["uname"] = User
		data["pwd"] = Pwd
		ret := httpGet("http://127.0.0.1:8080/login", data)
		fmt.Println(ret)
		err := json.Unmarshal([]byte(ret), u)
		if err != nil {
			fmt.Println(err.Error())
		}
		if (*u).Code == 0 {
			c.Write([]byte("\033[32m √ 登陆成功\033[0m\r\n"))
			*islogin = true
			time.Sleep(30000)
			c.Write([]byte("\033[2J"))
			c.Write([]byte([]byte("欢迎回来：" + (*u).Data.Name + "当前时间是：" + time.Now().String() + "\r\n")))
		} else {
			c.Write([]byte("\033[31m × 登陆失败\r\n    错误信息：" + (*u).Msg + "+\033[0m\r\n"))
		}
	} else if s == "/LOGOUT" || s == "/logout" {

	} else if s == "/View" || s == "/view" {

	} else if s == "/Write" || s == "/Write" {

	} else if s == "/register" || s == "/REGISTER" {
		c.Write([]byte("请输入你的用户名:\r\nregister>"))
		tmp := make([]byte, 512)
		User := ""
		Name := ""
		Pwd := ""
		for {
			n, _ := c.Read(tmp)
			if string(tmp[:n]) == "\r\n" {
				continue
			}
			User = string(tmp[:n])
			break
		}
		c.Write([]byte("请输入你的昵称:\r\nregister>"))
		for {
			n, _ := c.Read(tmp)
			if string(tmp[:n]) == "\r\n" {
				continue
			}
			Name = string(tmp[:n])
			break
		}
		c.Write([]byte("请输入你的密码:\r\nregister>"))

		for {
			n, _ := c.Read(tmp)
			if string(tmp[:n]) == "\r\n" {
				continue
			}
			Pwd = string(tmp[:n])
			break
		}
		fmt.Println(User, Name, Pwd)
		data := make(map[string]string)
		data["uname"] = User
		data["name"] = Name
		data["pwd"] = Pwd
		ret := httpGet("http://127.0.0.1:8080/register", data)
		fmt.Println(ret)
		var M LUser
		err := json.Unmarshal([]byte(ret), &M)
		if err != nil {
			fmt.Println(err.Error())
		}
		fmt.Println(M.Code, M.Msg)
		if M.Code != 0 {
			c.Write([]byte("\033[31m × 注册失败\r\n    错误信息：" + M.Msg + "+\033[0m\r\n"))
		} else {
			c.Write([]byte("\033[32m √ 注册成功\033[0m\r\n"))
		}
		c.Write([]byte(">"))

		return

	} else if s == "/cls" || s == "/CLS" {
		c.Write([]byte("\033[2J"))
		c.Write([]byte("\033[41;36m欢迎来到我也不知道叫什么好的论坛，请输入/HELP以显示帮助文档。\033[0m\r\n"))
		if *islogin == true {
			c.Write([]byte("欢迎回来：" + (*u).Data.Name + "当前时间是：" + time.Now().String() + "\r\n"))
		}
	} else if s == "\r\n" {
		c.Write([]byte(">"))
	} else if s == "" {
		return
	} else {
		c.Write([]byte("\033[31m × 无此命令！\033[0m\r\n\r\n>"))
	}

}
func HandleConnectcion(c net.Conn) {
	var User LUser
	islogin := false
	c.Write([]byte("\033[41;36m欢迎来到我也不知道叫什么好的论坛，请输入/HELP以显示帮助文档。\033[0m\r\n>"))
	ret := make([]byte, 128)
	defer c.Close()
	for {

		n, err := c.Read(ret)
		if err != nil {
			break
		}
		fmt.Println(string(ret[:n]) + "\n")
		fmt.Println(ret[:n])
		ParmarHandle(string(ret[:n]), c, &User, &islogin)
		//获取用户名
	}

}
func main() {
	l, err := net.Listen("tcp", ":23")
	if err != nil {
		fmt.Println(err.Error())
	}
	defer l.Close()
	for {
		conn, err := l.Accept()
		if err != nil {
			fmt.Println(err.Error())
			continue
		}
		go HandleConnectcion(conn)
	}

}
